package com.quectel.cms.controller.merchant;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.merchant.MerchantConfigSaveVo;
import com.quectel.cms.vo.merchant.MerchantVillageVo;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeConstants;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.merchant.dto.MerchantVillageDto;
import com.quectel.core.module.merchant.service.MerchantVillageService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.sys.module.sys.dto.SysCodeDto;
import com.quectel.sys.module.sys.service.SysCodeService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/03/28 13:09
 */
@RestController
@RequestMapping("merchantVillage")
@Tag(name = "MerchantVillageController", description = "小区与商户的关系表相关api")
public class MerchantVillageController extends BaseController {

    @DubboReference
    private MerchantVillageService merchantVillageService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private SysCodeService sysCodeService;

    /**
     * 商户关联信息保存
     *
     * @param merchantConfigSaveVo
     * @return
     */
    @PostMapping("configSave")
    @RequirePermissions(values = "merchantVillage:edit")
    @Operation(summary = "商户关联信息保存")
    public Response<Object> configSave(@RequestBody @Validated MerchantConfigSaveVo merchantConfigSaveVo) {
        merchantVillageService.updateConfig(merchantConfigSaveVo.getVillageId(), merchantConfigSaveVo.getList());
        return Response.ok();
    }

    /**
     * 商户关联列表
     *
     * @param villageId
     * @return
     */
    @GetMapping("merchantConfList")
    @RequirePermissions(values = "workOrderDirect:list")
    @Operation(summary = "商户关联列表")
    public Response<List<MerchantVillageDto>> merchantConfList(
            @Parameter(description = "小区id", required = true) @RequestParam Long villageId
    ) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));
        super.fillAuthorityData(request.getParams());

        VillageDto villageDto = villageService.selectCacheById(villageId);
        if (Objects.isNull(villageDto)) {
            return Response.error("小区不存在");
        }

        List<SysCodeDto> sysCodeDtos = Lists.newArrayList();
        Map<String, Object> queryCodeMap = new HashMap<>();
        queryCodeMap.put(LambdaUtil.getFieldName(SysCodeDto::getMark), SysCodeKeyConstants.MERCHANT_BUSINESS_TYPE);
        queryCodeMap.put(LambdaUtil.getFieldName(SysCodeDto::getType), SysCodeConstants.TypeLevelEnum.CATALOGUE.getType());
        queryCodeMap.put(LambdaUtil.getFieldName(SysCodeDto::getStatus), SystemConstants.ENABLE);
        List<SysCodeDto> catalogueList = sysCodeService.queryList(queryCodeMap);
        if (CollectionUtils.isNotEmpty(catalogueList)) {
            SysCodeDto sysCodeDto = catalogueList.get(0);
            queryCodeMap.remove(LambdaUtil.getFieldName(SysCodeDto::getMark));
            queryCodeMap.put(LambdaUtil.getFieldName(SysCodeDto::getType), SysCodeConstants.TypeLevelEnum.VALUE.getType());
            queryCodeMap.put(LambdaUtil.getFieldName(SysCodeDto::getParentId), sysCodeDto.getId());
            sysCodeDtos = sysCodeService.queryList(queryCodeMap);
            sysCodeDtos.sort((o1, o2) -> {
                if (o1.getSort() != null && o2.getSort() != null) {
                    return o1.getSort() - o2.getSort();
                }
                return 0;
            });
        }

        List<MerchantVillageDto> dblist = merchantVillageService.selectByVillageId(villageId);
        List<MerchantVillageDto> result = Lists.newArrayList();
        for (SysCodeDto sysCodeDto : sysCodeDtos) {
            result.add(dblist.parallelStream()
                    .filter(o -> o.getBusinessType().equals(sysCodeDto.getValue()))
                    .findFirst()
                    .orElseGet(() -> {
                        MerchantVillageDto merchantVillageDto = new MerchantVillageDto();
                        merchantVillageDto.setVillageId(villageDto.getId());
                        merchantVillageDto.setVillage(villageDto);
                        merchantVillageDto.setTenantId(villageDto.getTenantId());
                        merchantVillageDto.setBusinessType(sysCodeDto.getValue());
                        return merchantVillageDto;
                    }));
        }

        return Response.<List<MerchantVillageDto>>ok().wrap(result);
    }


    /**
     * 小区商户查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("villageList")
    @RequirePermissions(values = "merchantVillage:list")
    @Operation(summary = "分页列表")
    public Response<Page<MerchantVillageVo>> villageList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = villageService.queryTotal(request.getParams());

        List<VillageDto> list = null;
        if (total > 0) {
            list = villageService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        List<MerchantVillageVo> merchantVillageVos = CopyUtils.copyList(list, MerchantVillageVo.class);
        Map<String, Object> queryConfigMap = new HashMap<>();
        for (MerchantVillageVo merchantVillageVo : merchantVillageVos) {
            queryConfigMap.put(LambdaUtil.getFieldName(MerchantVillageDto::getVillageId), merchantVillageVo.getId());
            int configTotal = merchantVillageService.queryTotal(queryConfigMap);
            merchantVillageVo.setConfigNumber(configTotal);
        }

        Page<MerchantVillageVo> page = new Page<>(request.getPageNo(), request.getPageSize(), total, merchantVillageVos);
        return Response.<Page<MerchantVillageVo>>ok().wrap(page);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "merchantVillage:list")
    @Operation(summary = "分页列表")
    public Response<Page<MerchantVillageDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = merchantVillageService.queryTotal(request.getParams());

        List<MerchantVillageDto> list = null;
        if (total > 0) {
            list = merchantVillageService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<MerchantVillageDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<MerchantVillageDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "merchantVillage:edit")
    @Operation(summary = "查询单条记录")
    public Response<MerchantVillageDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (merchantVillageService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        MerchantVillageDto merchantVillageDto = merchantVillageService.selectById(id);

        return Response.<MerchantVillageDto>ok().wrap(merchantVillageDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "merchantVillage:info")
    @Operation(summary = "查询单条记录")
    public Response<MerchantVillageDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (merchantVillageService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        MerchantVillageDto merchantVillageDto = merchantVillageService.selectById(id);

        return Response.<MerchantVillageDto>ok().wrap(merchantVillageDto);
    }

    /**
     * 保存
     *
     * @param merchantVillageDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "merchantVillage:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated MerchantVillageDto merchantVillageDto) {

        //填充基础数据
        fillSaveCommonData(merchantVillageDto);

        merchantVillageService.save(merchantVillageDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param merchantVillageDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "merchantVillage:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated MerchantVillageDto merchantVillageDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(merchantVillageDto.getId()));
        if (merchantVillageService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(merchantVillageDto);

        merchantVillageService.updateById(merchantVillageDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "merchantVillage:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (merchantVillageService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        merchantVillageService.deleteBatch(ids);

        return Response.ok();
    }
}
